package com.lovo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lovo.model.dos.UserDO;
import com.lovo.model.dto.UserDTO;
import lombok.Data;

import java.util.Date;
import java.util.HashMap;

/**
 * @author luo
 * @description
 * @date 2020/12/1 17:16
 */
@Data
public class TokenUtil {

    private  static final  long EXPIRE_TIME=1000*30;
    private static  final  String TOKEN_SECRET="J177";

    public static String getToken(UserDO userDO){
        //过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //设置头信息
        HashMap<String, Object> header = new HashMap<>(4);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        //附带username和userID生成签名
        String token= JWT.create().withHeader(header)
                .withClaim("userName",userDO.getUserName())
                .withClaim("password",userDO.getUserPwd())
                .withClaim("permission",userDO.getPermissions())
                .withExpiresAt(date).sign(algorithm);
        return  token;

    }

    public static DecodedJWT verifyToken(String token){
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //构建认证对象
        JWTVerifier verifier = JWT.require(algorithm).build();
        try {
            //认证  ,认证失败抛出异常
            DecodedJWT jwt = verifier.verify(token);
            //拿到token中的内容
//            System.out.println(jwt.getClaim("userName").asString());
//            System.out.println(jwt.getClaim("password").asString());
            return jwt;
        }catch (Exception e){
            return null;
        }

    }


}
